
#include <stdio.h>
#include "Libbase.h"
#include "C_Thread.h"


C_Thread::C_Thread(unsigned int iProperties)
{
  m_iFlags = iProperties;
  m_iStatus = THREAD_STATUS_NOTSTARTED;
  dwId = NULL;
 
}


//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
C_Thread::~C_Thread()
{
}


//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
void C_Thread::Create()
{ 
  
    // Do some initialisations before starting the real job
    InitWork();

    // Now launch the thread
    unsigned long ulthreadID = 0;

    hThread = (HANDLE)CreateThread(NULL, 0, 
            (LPTHREAD_START_ROUTINE)C_Thread::StartRoutine, (void*)this, 0, &ulthreadID);
  
	if (ulthreadID == 0)
	{
		Log("Error","C_Thread::Create","thread create is failed");
	}
  

    

}






//------------------------------------------------------------------------------
// 
//------------------------------------------------------------------------------
void C_Thread::Stop()
{
 
      // Ask the user work routine to stop its normal processing
      StopWork();
  

     
      WaitForSingleObject (hThread, 1000);


      // Cleaning
      CleanWork();
	
   
	  hThread = NULL;
}






//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
bool C_Thread::IsRunning()
{
  return (m_iStatus == THREAD_STATUS_STARTED);
}


//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
// The purpose of this routine is only to allow the "extern C" pthread_create
// functions to call the DoWork() C++ method
//------------------------------------------------------------------------------
void* C_Thread::StartRoutine(void* pThread)
{
  C_Thread* pThis = (C_Thread*)pThread;
  
  pThis->m_iStatus = THREAD_STATUS_STARTED;
  pThis->DoWork(); 
  pThis->m_iStatus = THREAD_STATUS_STOPPED;

  return NULL;
}



